import pygame
import sys
import random
from datetime import datetime, timedelta
from models import Player, Team, Match, Message
from ui import GameUI
from utils import init_fonts, generate_player_name, generate_player_bio, check_stage_conditions, check_special_events, SCREEN_WIDTH, SCREEN_HEIGHT

class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("足球模拟游戏")
        self.clock = pygame.time.Clock()
        self.font, self.small_font, self.large_font = init_fonts()
        self.ui = GameUI(self.screen, self.font, self.small_font, self.large_font)

        # 初始化游戏状态
        self.current_screen = "message"  # 修改初始屏幕为消息页面
        self.game_over = False
        self.current_date = datetime(1985, 5, 1)  # 修改初始日期为1985年5月1日
        self.stage = 1
        self.year = 3
        self.match_count = 1
        self.fake_mission_count = 0
        self.consecutive_top_three = 0
        self.bribe_used = False
        self.stamina_choice = 1
        self.opponent_match_stamina = 5
        self.must_lose = False
        self.match_processed = False
        self.ending = "游戏结束"
        self.task_completed = True  # 完成每年必要任务，check_annual_must_tasks判定
        self.promotion_names = [
            "四川大河", "云南红塔", "陕西国力", "深圳平安",
            "北京宽利", "广州松日", "吉林敖东", "厦门远华"
        ]
        # 初始化球队和球员
        self.teams = []
        self.user_team = None
        self.init_teams()
        self.init_players()

        # 初始化赛程
        self.season_schedule = []
        self.current_match = None
        self.generate_season_schedule()

        # 初始化消息
        self.messages = []
        self.add_season_start_messages()
    def add_season_start_messages(self):
        #对于任务在check_annual_must_tasks中，要在赛季开始时添加消息
        #清除去年的消息
        self.messages = []
        # 第一年赛季开始消息
        if self.year == 1 and self.stage == 1:
            #第一年任务，不要垫底
            self.add_message("系统", "市足协：本赛季排名不得为最后两名，否则将被淘汰。", self.current_date)
            # 鼓励消息
            self.add_message(
                "系统", 
                "带上你的四川全兴酒队出发吧！在中国足球的混沌年代，活下去就是最大的胜利！\n" +
                "提示：密切关注消息通知，足协的'指示'可能随时到来...",
                self.current_date
            )
            # 比赛安排说明
            self.add_message(
                "系统", 
                "【1985年赛季安排】\n" +
                "• 比赛地点：北京工人体育场\n" +
                "• 赛制：赛会制（我们要跟着全运会一起走，所有球队在短期内完成全部比赛）\n" +
                "• 赛程：隔天比赛，共14场（对阵其他7支球队主客场各一场）\n" +
                "• 体力恢复：每次比赛后恢复2点体力（受赛会制高密度赛程限制）\n" ,
                self.current_date
            )
            # 游戏玩法说明
            self.add_message(
                "系统", 
                "【游戏玩法】每次比赛球员会消耗体力并与对方掷骰子比大小：\n" +
                "1. 点数大者获得球权\n" +
                "2. 连续3次点数大则进球\n" +
                "3. 比赛后球员会恢复体力\n" +
                "4. 作为球队经理，你可以指导球队每次比赛可用的体力分配\n" +
                "记住，在中国足球的江湖里，有时候'演的好'比'踢的好'更重要！",
                self.current_date
            )
            # 欢迎消息
            self.add_message(
                "系统", 
                "欢迎来到假B足球联赛！这是中国足球职业化初期的荒诞舞台，你将带领球队在乱象中生存。",
                self.current_date
            )
        if self.year == 2 and self.stage == 1:
            # 第二年开局消息
            self.add_message("系统公告", "经过一年的磨砺，你已经成长为一名熟练的球队管理者。新的赛季将带来更严峻的挑战，继续你的征程吧！", self.current_date)
            self.add_message("联赛通知", "为与国际接轨，本赛季起采用主客场双循环赛制。每两场比赛间隔7天，球员将获得更科学的休整周期。", self.current_date)
            self.add_message("市领导指示", "体育局张局长今日莅临训练基地强调：'主场比赛是展示城市形象的窗口，必须确保每一场都打出精神面貌！'", self.current_date)
            self.add_message("升降级规则", "本赛季结束后，积分榜倒数2名将直接降级至乙级联赛。这是职业化改革的重要一步，也是对所有俱乐部的考验，不要降级。", self.current_date)    
        # 第三年赛季开始消息
        if self.year == 3 and self.stage == 1:
            self.add_message(
                "市足协", 
                "感谢八一红星队在关键时刻的支持，使我队成功保级。这份体制内的情谊，务必在公开场合表达感谢。", 
                self.current_date
            )
            self.add_message(
                "中国足协", 
                "为备战世界杯预选赛，需要征兆联赛球队和国家队热身，球队不会被淘汰", 
                self.current_date
            )
            self.add_message(
                "联赛办公室", 
                "为培养青年足球人才，决定组建国家二队将以独立身份参加本赛季。", 
                self.current_date
            )    
            
            
            
    def init_teams(self):
        # 初始化球队
        if self.stage == 1:
            # 第一阶段球队
            team_names = [
                "四川全兴酒",  # 玩家球队
                #"重庆山城火锅",
                #"广州太阳神药",
                #"延边冷面王",
                #"沈阳海狮电器",
                "青岛啤酒花",
                "天津麻花",
                "八一红星"
            ]
            prototypes = ["原型1", "原型2", "原型3", "原型4", "原型5", "原型6", "原型7", "原型8"]
        elif self.stage == 2:
            # 第二阶段球队（2000年前后国足和中超知名球队变体）
            team_names = [
                "大连实德船",  # 玩家球队
                "上海申花花",
                "山东鲁能能",
                "北京国安安",
                "天津泰达达",
                "武汉黄鹤楼",
                "深圳健力宝",
                "辽宁抚顺钢"
            ]
            prototypes = ["原型1", "原型2", "原型3", "原型4", "原型5", "原型6", "原型7", "原型8"]
        else:
            # 第三阶段球队（2008年前后国足和中超知名球队变体）
            team_names = [
                "北京国安",  # 玩家球队
                "山东鲁能泰山",
                "上海申花文广",
                "天津康师傅",
                "杭州绿城",
                "长春亚泰",
                "河南建业",
                "恒大地产"
            ]
            prototypes = ["原型1", "原型2", "原型3", "原型4", "原型5", "原型6", "原型7", "原型8"]

        self.teams = []  # 清空现有球队
        for name, prototype in zip(team_names, prototypes):
            team = Team(name, prototype)
            team.balance = 10000  # 初始资金
            self.teams.append(team)

        # 设置用户球队（始终是第一个）
        self.user_team = self.teams[0]

    def init_players(self):
        # 为每个球队初始化球员
        for team in self.teams:
            for _ in range(5):  # 每个球队5名球员
                name = generate_player_name()
                ability = random.randint(1, 9)
                player = Player(name, ability)
                player.bio = generate_player_bio(name)
                team.add_player(player)

    def generate_season_schedule(self):
        # 生成赛季赛程
        self.season_schedule = []
        match_number = 1
        team_count = len(self.teams) 
        max_match_count = 2 * ( team_count - 1) # 设置最大match_count为球队数量-1的2倍

        # 创建一个字典来跟踪每个match_count中已使用的球队
        match_count_teams = {i: set() for i in range(1, max_match_count + 1 )}

        # 用户球队的比赛
        for other_team in self.teams:
            if other_team != self.user_team:
                # 为主场比赛寻找可用的match_count
                for mc in range(1, max_match_count + 1):
                    if self.user_team not in match_count_teams[mc] and other_team not in match_count_teams[mc]:
                        self.season_schedule.append(Match(match_number, mc, self.user_team, other_team, self.stage, self.year, is_user_involved=True))
                        match_number += 1
                        match_count_teams[mc].add(self.user_team)
                        match_count_teams[mc].add(other_team)
                        break

                # 为客场比赛寻找可用的match_count
                for mc in range(1, max_match_count + 1):
                    if self.user_team not in match_count_teams[mc] and other_team not in match_count_teams[mc]:
                        self.season_schedule.append(Match(match_number, mc, other_team, self.user_team, self.stage, self.year, is_user_involved=True))
                        match_number += 1
                        match_count_teams[mc].add(self.user_team)
                        match_count_teams[mc].add(other_team)
                        break

        # 其他球队之间的比赛
        for i in range(len(self.teams)):
            for j in range(len(self.teams)):
                if self.teams[i] != self.user_team and self.teams[j] != self.user_team and i != j:
                    # 寻找可用的match_count
                    for mc in range(1, max_match_count + 1):
                        if self.teams[i] not in match_count_teams[mc] and self.teams[j] not in match_count_teams[mc]:
                            # 安排主客场比赛
                            # 为主场比赛创建Match对象并随机生成进球数
                            home_match = Match(match_number, mc, self.teams[i], self.teams[j], self.stage, self.year)
                            home_match.home_goals = random.randint(0, 5)
                            home_match.away_goals = random.randint(0, 5)
                            self.season_schedule.append(home_match)
                            match_number += 1
                            match_count_teams[mc].add(self.teams[i])
                            match_count_teams[mc].add(self.teams[j])
                            break

        # 打乱赛程顺序
        self.season_schedule.sort(key=lambda x: (x.match_count, x.match_number))

        # 重新编号
        for i, match in enumerate(self.season_schedule):
            match.match_number = i + 1

        #self.season_schedule = new_schedule

    def modify_match_score(self, match_count, match_number, home_goals, away_goals):
        # 修改比赛比分
        for match in self.season_schedule:
            if match.match_number == match_number:
                match.home_goals = home_goals
                match.away_goals = away_goals
                match.completed = True
                break
 
    def get_next_user_match(self):
        # 获取下一场用户参与的比赛
        for match in self.season_schedule:
            if match.is_user_involved and not match.completed:
                return match
        return None

    def get_ranking(self, use_head_goals=False, use_two_year_points=False):
        # 计算球队排名
        sorted_teams = sorted(self.teams, key=lambda x: (
            x.points + x.last_year_points if use_two_year_points else x.points,
            x.calculate_goal_difference(),
            x.head_goals if use_head_goals else x.goals_scored
        ), reverse=True)
        return sorted_teams

    def add_message(self, source, content, date, is_task=False, completed=False):
        # 添加消息
        self.messages.append(Message(source, content, date, is_task, completed))

    def recover_stamina(self):
        # 恢复所有球队球员的体力
        if self.year == 1:
            amount = 2
        else:
            amount = 7
        for team in self.teams:
            team.recover_players_stamina(amount, self.stage)

    def handle_fake_mission(self, match):
        # 处理假球任务
        # 假球任务从第二赛季开始触发
        if self.stage >= 2:
            # 20%的概率触发假球任务
            return random.random() < 0.2
        return False  # 第一赛季不触发假球任务

    def advance_stage(self):
        self.stage += 1
        # 推进到新阶段
        stage_names = {1: "假B城市足协", 2: "假B俱乐部", 3: "种超俱乐部"}
        self.add_message("系统", f"进入{stage_names[self.stage]}阶段！", self.current_date)

        # 重置一些状态
        self.fake_mission_count = 0
        self.consecutive_top_three = 0
        self.year = 0  # 新阶段重新开始计数年份
        # 初始化新球队和球员
        self.init_teams()
        self.init_players()

        # 进行新一年
        if self.stage==2:
            self.current_date = datetime(1994, 1, 1)
        elif self.stage==3:
            self.current_date = datetime(2004, 1, 1)
        self.start_new_year()

    def start_new_year(self):
        # 开始新的一年
        self.year += 1
        self.current_date = datetime(self.current_date.year + 1, 1, 1)
        self.add_message("系统", f"新的一年开始了！现在是{self.year}年", self.current_date)
        self.add_season_start_messages()
        self.current_screen = "message"
        # 保存上一年积分
        for team in self.teams:
            team.last_year_points = team.points
            team.points = 0
            team.goals_scored = 0
            team.goals_conceded = 0
            team.head_goals = 0
            team.matches_played = 0

        # 球员能力提升
        for team in self.teams:
            if team != self.user_team:
                for player in team.players:
                    if random.random() < 0.3:
                        player.ability = min(9, player.ability + 1)
            else:
                for player in team.players:
                    player.ability = max(1, player.ability - 1)

        # 处理升降级（第二阶段及以后）
        if self.stage >= 2 and self.year > 1:
            ranking = self.get_ranking()
            #删除ranking中的用户球队
            ranking.remove(self.user_team)
            # 降级最后两名球队
            relegated_teams = ranking[-2:]
            #将降级球队名称加入promotion_names
            for team in relegated_teams:
                self.promotion_names.append(team.name)
            for team in relegated_teams:
                self.add_message("系统", f"{team.name}降级离开了联赛！", self.current_date)
                self.teams.remove(team)
            
            # 新增两个升级球队
            new_team_names = self.get_promotion_team_names()
            for name in new_team_names:
                # 创建新球队
                new_team = Team(name, "升级球队")
                new_team.balance = 10000  # 初始资金
                self.teams.append(new_team)
                self.add_message("系统", f"{name}升级进入联赛！", self.current_date)
            
            # 为新球队初始化球员（能力值和为30）
            for team in self.teams[-2:]:
                self.init_players_for_promotion(team)
            

        # 生成新赛季赛程
        self.generate_season_schedule()
        self.match_count = 1
        self.match_number = 1

    def get_promotion_team_names(self):
        # 阶段2的升级球队名称库（2000年前后知名球队变体）
        
        
        # 确保不重复选择已存在的球队名称
        existing_names = [team.name for team in self.teams]
        available_names = [name for name in self.promotion_names[2:] if name not in existing_names]
        
        # 随机选择两个名称
        if len(available_names) >= 2:
            return random.sample(available_names, 2)
    def init_players_for_promotion(self, team):
        # 为升级球队初始化球员，能力值和为30
        team.players = []
        total_ability = 30
        num_players = 5
        
        # 生成4名随机能力的球员
        abilities = []
        for _ in range(num_players - 1):
            ability = random.randint(1, 8)
            abilities.append(ability)
            total_ability -= ability
        
        # 最后一名球员的能力值为剩余值
        abilities.append(max(1, total_ability))
        
        # 创建球员
        for ability in abilities:
            name = generate_player_name()
            player = Player(name, ability)
            player.bio = generate_player_bio(name)
            team.add_player(player)    
    def print_ranking(self):
        """打印赛季结束排名"""
        sorted_teams = self.get_ranking(
            use_head_goals=((self.stage == 1 and self.year >= 4) or (self.stage >= 2)),
            use_two_year_points=(self.stage >= 2 and self.year >= 4)
        )

        self.add_message("联赛办公室", "赛季最终排名：", self.current_date)
        for i, team in enumerate(sorted_teams[:3]):
            self.add_message("联赛办公室", f"{i+1}. {team.name} - 积分: {team.points}", self.current_date)

        # 处理降级球队
        if self.year > 1:  # 第一年不降级
            relegated = sorted_teams[-2:]
            for team in relegated:
                self.add_message("联赛办公室", f"{team.name} 降级", self.current_date)

    def run(self):
        """游戏主循环"""
        # 添加计时器变量
        last_update_time = pygame.time.get_ticks()
        update_interval = 100  # 0.1秒 = 100毫秒
        while True:
            current_time = pygame.time.get_ticks()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                #比赛界面自动更新
                if self.current_screen == "match":
                        # 比赛界面
                    #buttons = self.ui.draw_match_screen(self)
                    if self.current_match:
                        # 自动更新比赛状态（每秒一次）
                        if not self.current_match.completed and current_time - last_update_time >= update_interval:
                            # 如果比赛未结束，自动进行下一步
                            self.current_match.play_step(self.user_team, self.bribe_used, self.must_lose)
                            # 重置计时器
                            last_update_time = current_time
                        
                            
                if event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = event.pos

                    if self.game_over:
                        # 游戏结束界面
                        restart_button = self.ui.draw_game_over_screen(self)
                        if restart_button.collidepoint(mouse_pos):
                            # 重新开始游戏
                            self.__init__()
                    elif self.current_screen == "main":
                        # 主界面按钮点击
                        buttons = self.ui.draw_main_screen(self)
                        for i, button in enumerate(buttons):
                            if button.collidepoint(mouse_pos):
                                if i == 0:  # 消息
                                    self.current_screen = "message"
                                    # 标记所有消息为已读
                                    for msg in self.messages:
                                        msg.read = True
                                elif i == 1:  # 参赛
                                    self.current_screen = "match_setup"
                                    self.current_match = self.get_next_user_match()
                                    self.bribe_used = False
                                    self.stamina_choice = 1
                                    self.must_lose = False
                                elif i == 2:  # 队员信息
                                    self.current_screen = "team_info"
                                elif i == 3:  # 积分信息
                                    self.current_screen = "standings"
                                elif i == 4:  # 参赛信息
                                    self.current_screen = "fixtures"

                    elif self.current_screen == "message":
                        # 消息界面返回
                        back_button = self.ui.draw_message_screen(self)
                        if back_button.collidepoint(mouse_pos):
                            self.current_screen = "main"

                    elif self.current_screen == "team_info":
                        # 球队信息界面返回
                        back_button = self.ui.draw_team_info_screen(self)
                        if back_button.collidepoint(mouse_pos):
                            self.current_screen = "main"

                    elif self.current_screen == "standings":
                        # 积分榜界面返回
                        back_button = self.ui.draw_standings_screen(self)
                        if back_button.collidepoint(mouse_pos):
                            self.current_screen = "main"

                    elif self.current_screen == "fixtures":
                        # 赛程界面返回
                        back_button = self.ui.draw_fixtures_screen(self)
                        if back_button.collidepoint(mouse_pos):
                            self.current_screen = "main"
                    elif self.current_screen == "season_summary":
                        # 赛季总结页面
                        back_button = self.ui.draw_season_summary_screen(self)
                        if back_button.collidepoint(mouse_pos):
                            self.current_screen = "main"
                            # 开始新赛季准备
                             # 检查阶段条件
                            if check_stage_conditions(self):
                                if self.stage < 3:
                                    self.advance_stage()
                                else:
                                    # 游戏结束
                                    self.game_over = True
                                    self.ending = "恭喜你完成了所有阶段目标，游戏结束！"
                            else:
                                # 开始新的一年
                                self.start_new_year()
                    elif self.current_screen == "match_setup":
                        # 比赛设置界面
                        buttons = self.ui.draw_match_setup_screen(self)
                        if buttons["back"].collidepoint(mouse_pos):
                            self.current_screen = "main"
                            self.current_match = None
                        elif buttons["start"].collidepoint(mouse_pos):
                            # 应用体力设置
                            for player in self.user_team.players:
                                if self.stamina_choice == 1:
                                    # 全部使用，保持当前体力
                                    player.match_stamina = player.stamina
                                elif self.stamina_choice == 2:
                                    # 使用一半
                                    player.match_stamina = max(1, player.stamina // 2)
                                elif self.stamina_choice == 3:
                                    # 使用2点
                                    player.match_stamina = 2
                            if self.current_match.home_team == self.user_team:
                                for player in self.current_match.away_team.players:
                                    player.match_stamina = self.current_match.opponent_match_stamina
                            elif self.current_match.away_team == self.user_team:
                                #在第一阶段第二年，八一队使用最少体力
                                if self.stage == 1 and self.year == 2 and self.current_match.home_team.name == "八一红星":
                                    for player in self.current_match.home_team.players:
                                        player.match_stamina = 2
                                    #插入消息，八一队使用最少体力
                                    self.add_message("系统", "八一队看你们要辛苦保级，决定放水", self.current_date)
                                for player in self.current_match.home_team.players:
                                    player.match_stamina = self.current_match.opponent_match_stamina    
                            
                            # 记录体力投入事件
                            # 计算主客场球队的平均体力投入
                            home_avg_stamina = sum(p.match_stamina for p in self.current_match.home_team.players) / len(self.current_match.home_team.players) if self.current_match.home_team.players else 0
                            away_avg_stamina = sum(p.match_stamina for p in self.current_match.away_team.players) / len(self.current_match.away_team.players) if self.current_match.away_team.players else 0

                            # 修改为字符串格式的事件记录
                            stamina_event = f' 体力投入: 主场{self.current_match.home_team.name}投入体力: {home_avg_stamina:.1f}, 客场{self.current_match.away_team.name}投入体力: {away_avg_stamina:.1f}'
                            self.current_match.events.append(stamina_event)

                            # 检查行贿是否有效
                            if self.stage >= 2 and self.bribe_used:
                                if self.user_team.balance >= 3000:
                                    self.user_team.balance -= 3000
                                    self.add_message("财务处", f"行贿支出3000元，剩余余额{self.user_team.balance}元", self.current_date)
                                else:
                                    self.bribe_used = False
                                    self.add_message("财务处", "余额不足，无法行贿", self.current_date)

                            self.current_screen = "match"
                            # 重置计时器，确保进入比赛界面后立即开始自动刷新
                            last_update_time = pygame.time.get_ticks()
                        elif buttons["stamina1"].collidepoint(mouse_pos):
                            self.stamina_choice = 1
                        elif buttons["stamina2"].collidepoint(mouse_pos):
                            self.stamina_choice = 2
                        elif buttons["stamina3"].collidepoint(mouse_pos):
                            self.stamina_choice = 3
                        elif self.stage >= 2:
                            if buttons["bribe_yes"].collidepoint(mouse_pos):
                                self.bribe_used = True
                            elif buttons["bribe_no"].collidepoint(mouse_pos):
                                self.bribe_used = False

                    elif self.current_screen == "match":
                        # 比赛界面
                        buttons = self.ui.draw_match_screen(self)
                        if self.current_match:
                            # 自动更新比赛状态（每秒一次）
                            if not self.current_match.completed and current_time - last_update_time >= update_interval:
                                # 如果比赛未结束，自动进行下一步
                                
                                self.current_match.play_step(self.user_team, self.bribe_used, self.must_lose)
                                # 重置计时器
                                last_update_time = current_time

                            # 检查是否点击返回按钮
                            mouse_pos = pygame.mouse.get_pos()
                            mouse_clicked = pygame.mouse.get_pressed()[0]  # 检查左键是否被点击
                            if "back" in buttons and buttons["back"].collidepoint(mouse_pos) and mouse_clicked:
                                # 如果比赛已完成且未处理，执行finalize_match
                                # 更新积分榜
                                self.update_standings()
                                # 处理比赛结果
                                self.finalize_match()
                               
                                self.current_match = None
                                self.match_processed = False

                        elif "back" in buttons and buttons["back"].collidepoint(pygame.mouse.get_pos()):
                            self.current_screen = "main"
                            self.current_match = None

            # 绘制当前界面
            if self.game_over:
                self.ui.draw_game_over_screen(self)
            elif self.current_screen == "main":
                self.ui.draw_main_screen(self)
            elif self.current_screen == "message":
                self.ui.draw_message_screen(self)
            elif self.current_screen == "team_info":
                self.ui.draw_team_info_screen(self)
            elif self.current_screen == "standings":
                self.ui.draw_standings_screen(self)
            elif self.current_screen == "fixtures":
                self.ui.draw_fixtures_screen(self)
            elif self.current_screen == "match_setup":
                self.ui.draw_match_setup_screen(self)
            elif self.current_screen == "match":
                self.ui.draw_match_screen(self)

            pygame.display.flip()
            self.clock.tick(30)

    def update_standings(self):
        """更新积分榜数据"""
        # 重置所有球队的积分
        for team in self.teams:
            team.points = 0
            team.wins = 0
            team.draws = 0
            team.losses = 0
            team.goals_scored = 0 #进球数
            team.goals_conceded = 0 #失球数 
            team.goal_difference = 0
            team.matches_played += 1
        #修改当前match_count的比赛为完成
        for match in self.season_schedule:
            if match.match_count == self.current_match.match_count :
                match.completed = True
        # 计算所有已完成比赛的积分
        for match in self.season_schedule:
            if match.completed:
                home_team = match.home_team
                away_team = match.away_team
                home_goals = match.home_goals
                away_goals = match.away_goals

                # 更新进球数
                home_team.goals_scored += home_goals
                home_team.goals_conceded += away_goals
                away_team.goals_scored += away_goals
                away_team.goals_conceded += home_goals

                # 计算净胜球
                home_team.goal_difference = home_team.goals_scored - home_team.goals_conceded
                away_team.goal_difference = away_team.goals_scored - away_team.goals_conceded

                # 更新积分
                if home_goals > away_goals:
                    home_team.wins += 1
                    home_team.points += 3
                    away_team.losses += 1
                elif home_goals < away_goals:
                    away_team.wins += 1
                    away_team.points += 3
                    home_team.losses += 1
                else:
                    home_team.draws += 1
                    home_team.points += 1
                    away_team.draws += 1
                    away_team.points += 1

    def finalize_match(self):
        """处理比赛结束后的逻辑"""
        if self.current_match is None or not self.current_match.completed:
            return

        # 检查假球任务是否完成
        if self.must_lose:
            # 检查是否真的输了
            if ((self.user_team == self.current_match.home_team and 
                 self.current_match.home_goals < self.current_match.away_goals) or 
                (self.user_team == self.current_match.away_team and 
                 self.current_match.away_goals < self.current_match.home_goals)):
                # 完成假球任务
                self.fake_mission_count += 1
                self.user_team.balance += 3000
                self.add_message("足协", f"完成假球任务，获得奖金3000元，当前余额{self.user_team.balance}元", self.current_date)

                # 更新任务状态
                for msg in self.messages:
                    if (msg.source == "足协" and msg.is_task and not msg.completed and 
                        f"{self.current_match.home_team.name}vs{self.current_match.away_team.name}" in msg.content):
                        msg.completed = True
            else:
                self.add_message("足协", "未完成假球任务，下场比赛对方将全力以赴", self.current_date)
                # 下场比赛对方使用全部体力
                # 这里可以设置一个标记，影响下一场比赛
        # 推进match_count到下一轮
        self.match_count += 1
        # 推进日期
        days_to_add = 2 if (self.stage == 1 and self.year == 1) else 7
        self.current_date += timedelta(days=days_to_add)

        # 恢复体力
        self.recover_stamina()

        # 检查特殊事件
        check_special_events(self)
        
        # 检查所有比赛是否完成（包括AI之间的比赛）
        all_matches_completed = all(m.completed for m in self.season_schedule)
        if all_matches_completed :
            # 检查年度必须任务
                
                if not self.check_annual_must_tasks():
                    self.game_over = True
                    self.ending = "市体育局通报：因未能完成年度主场胜利指标，你已被免去主教练职务。游戏结束。"
                else:
                    # 显示赛季总结页面
                    self.current_screen = "season_summary"
                    self.add_message("系统", f"{self.year}赛季结束！点击查看年度总结", self.current_date)

           
        else:
            self.current_screen = "main"

        # 标记比赛已处理
        self.match_processed = True

        # 按积分排序
        self.teams.sort(key=lambda x: (-x.points, -x.goal_difference, -x.goals_scored))
    def check_annual_must_tasks(self):
        tasks = []
        self.task_completed = True  # 默认完成所有任务
        # 第一阶段第一年任务：排名不能为最后两名
        if self.stage == 1 and self.year == 1:
            ranking = self.get_ranking()
            user_rank = ranking.index(self.user_team) + 1  # 排名从1开始
            team_count = len(ranking)
            # 检查是否为最后两名
            if user_rank >= team_count - 1:
                self.task_completed = False
                tasks.append({
                    'description': f'球队排名不得为最后两名 (实际排名: {user_rank})',
                    'completed': False
                })
        # 第一阶段第二年任务：主场胜利次数 > 球队数 - 2
        elif self.stage == 1 and self.year == 2:
            team_count = len(self.teams)
            required_wins = team_count - 2
            home_wins = 0
            
            # 统计主场胜利次数
            for match in self.season_schedule:
                if match.home_team == self.user_team and match.completed and match.home_score > match.away_score:
                    home_wins += 1
            
            task_completed = home_wins > required_wins
            tasks.append({
                'description': f'主场胜利次数超过{required_wins}场 (实际完成: {home_wins}场)',
                'completed': task_completed
            })
            
            if not task_completed:
                self.task_completed = False
        elif self.stage == 1 and self.year == 3:
            # 检查主场对阵八一队是否输球
            bayi_loss = True
            for match in self.season_schedule:
                if (match.home_team == self.user_team and 
                    match.away_team.name == "八一红星" and 
                    match.completed):
                    if match.home_goals >= match.away_goals:
                        bayi_loss = False
                        break
            if not bayi_loss:
                self.task_completed = False
                tasks.append({
                    'description': '八一红星队的人情要不要还',
                    'completed': False
                })
            # 检查排名是否为最后三名
            if user_rank >= team_count - 2:
                self.task_completed = False
                tasks.append({
                    'description': f'广州队参与国足热身，不用淘汰，你们被淘汰了 (实际排名: {user_rank})',
                    'completed': False
                })

        return self.task_completed
    def check_annual_tasks(self):
        """检查年度任务完成情况"""
        tasks = []
        ranking = self.get_ranking()
        user_rank = ranking.index(self.user_team) + 1

        if self.stage == 1:
            tasks.append({
                "description": "获得领导认可",
                "completed": self.year >= 2  # 假设第二年自动获得
            })
            tasks.append({
                "description": "赛季排名前三",
                "completed": user_rank <= 3
            })
        elif self.stage == 2:
            tasks.append({
                "description": "完成至少1次假球任务",
                "completed": self.fake_mission_count >= 1
            })
            tasks.append({
                "description": "八一队让球任务",
                "completed": self.year == 3 and self.fake_mission_count >= 1
            })
        else:
            tasks.append({
                "description": "保持联赛前四",
                "completed": user_rank <= 4
            })
            tasks.append({
                "description": "球队总积分超过50分",
                "completed": self.user_team.points >= 50
            })
        return tasks

if __name__ == "__main__":
    game = Game()
    game.run()